import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/student/ProfileStudent.dart';
import 'package:ichinesereader/utils/log.dart';
import '../../themes/appTheme.dart';

class SwitchParentChildDialog extends StatefulWidget {
  SwitchParentChildDialog({
    Key? key,
  }) : super(key: key);

  _SwitchParentChildDialogState createState() =>
      new _SwitchParentChildDialogState();
}

class _SwitchParentChildDialogState extends State<SwitchParentChildDialog> {
  var box = Hive.box('appconfig');
  final UserController _userController = Get.find();
  final BooksController _booksController = Get.find();
  final ReportsController _reportsController = Get.put(ReportsController());
  String _childUserName = '';

  @override
  void initState() {
    _childUserName = box.get(CacheManagerKey['currentchild'].toString()) ?? '';
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text('Please Choose Child'.tr),
      titleTextStyle: TextStyle(
          fontFamily: 'Montserrat',
          letterSpacing: 1,
          color: Get.isDarkMode
              ? Get.theme.primaryColorDark
              : Get.theme.primaryColorLight,
          fontSize: 20),
      backgroundColor: Get.theme.primaryColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(12),
        ),
      ),
      content: Container(
        width: 450,
        height: 370,
        child: Column(children: [
          Container(
            child: FormBuilder(
              child: FormBuilderChoiceChip(
                decoration: InputDecoration(
                  prefixIcon: Padding(
                    padding: const EdgeInsets.all(2.0),
                    child: Tooltip(
                        message: 'Choose Child'.tr,
                        child: Icon(Icons.people_alt_rounded)),
                  ),
                  prefixIconColor: Get.isDarkMode
                      ? Colors.black
                      : Colors.white.withOpacity(0.8),
                ),
                spacing: 9.0,
                backgroundColor:
                    Get.isDarkMode ? Get.theme.primaryColor : Colors.blueGrey,
                selectedColor: Get.isDarkMode
                    ? Colors.white
                    : Theme.of(context).primaryColorDark,
                initialValue: _userController.parentChildren.firstWhere(
                    (element) => element.userName == _childUserName),
                name: 'parentchild_chip',
                onChanged: (value) {
                  if (value == null) return;
                  var v = value as ProfileStudent;
                  if (v.classResps == null || v.classResps!.isEmpty)
                    return null;
                  try {
                    _userController.getParentClassOptions(value.userName);
                    String _classId = value.classResps![0].classId.toString();
                    String _userName = value.userName.toString();
                    if (Get.currentRoute == '/parent/reports') {
                      _userController
                          .updateParentSelectedClass(value.classResps![0]);
                      _reportsController.refetchStudentPersonalReport(
                          _classId, _userName);
                    }
                    if (Get.currentRoute == '/parent/leveledreadings') {
                      _booksController
                          .fetchProgressReadingItemsForChild(value.userName!);
                    } else if (Get.currentRoute == '/parent/myfavorites') {
                      _booksController
                          .fetchBookAllFoldersForChild(_userName)
                          .then((folders) {
                        if (folders.isNotEmpty) {
                          if (_booksController.currentBookFolder.value.id !=
                                  null &&
                              folders.length > 0) {
                            int index = folders.indexWhere((element) =>
                                element.id ==
                                _booksController.currentBookFolder.value.id);
                            if (index != -1) {
                              _booksController
                                  .fetchChildFavoriteReadingItemsByFolder(
                                      _booksController
                                          .currentBookFolder.value.id
                                          .toString(),
                                      _userName);
                            } else {
                              _booksController.setCurrentBookFolder(folders[0]);
                            }
                          } else if (_booksController
                                      .currentBookFolder.value.id ==
                                  null &&
                              folders.length > 0) {
                            _booksController.setCurrentBookFolder(folders[0]);
                          } else {
                            if (folders.isNotEmpty) {
                              _booksController.setCurrentBookFolder(folders[0]);
                            }
                          }
                        }
                      });
                    }
                    Navigator.of(context).pop();
                  } catch (error) {
                    Log.debug(error);
                  }
                },
                options: _userController.parentChildren
                    .where((element) =>
                        element.classResps != null &&
                        element.classResps!.isNotEmpty)
                    .map((student) => FormBuilderChipOption<ProfileStudent>(
                          value: student,
                          child: Text(
                            '${student.firstName} ${student.lastName}'
                                .toString(),
                            style: TextStyle(
                              color: Get.isDarkMode
                                  ? Colors.black
                                  : Get.theme.primaryColorLight,
                              fontSize: 16,
                              letterSpacing: 1,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ))
                    .toList(),
              ),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              MaterialButton(
                color: Get.isDarkMode
                    ? AppTheme.colors.darkTheme2
                    : Get.theme.primaryColorLight,
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text(
                  'Close'.tr,
                  style: TextStyle(color: Get.theme.primaryColorDark),
                ),
              ),
            ],
          ),
        ]),
      ),
    );
  }
}
